package com.oh.iris.server.handler;

import com.oh.core.common.cache.ChannelStore;
import com.oh.core.common.constant.CommandEnum;
import com.oh.core.common.constant.SerializationAlgorithm;
import com.oh.core.common.utils.MessageUtils;
import com.oh.core.entity.MessageEntity;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 心跳处理
 */
@ChannelHandler.Sharable
@Component
public class HeartBeatServer extends ChannelInboundHandlerAdapter {

    private final Logger log = LoggerFactory.getLogger(HeartBeatServer.class);
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("服务端触发心跳检测");
        if (evt instanceof IdleStateEvent) {//超时事件
            IdleStateEvent idleEvent = (IdleStateEvent) evt;
            if (idleEvent.state() == IdleState.READER_IDLE) {//读
                log.warn("未检测到心跳【读取】");
                byte [] content = "【服务端】未检测到心跳，连接断开，请重新连接！".getBytes();
                MessageUtils.channelMsg(ctx.channel(), new MessageEntity(CommandEnum.MESSAGE_REQUEST.getCommand(), content));
                ChannelStore.removeChannel(ctx.channel().id().asLongText());
                ctx.channel().close();
                log.info("连接数 {}", ChannelStore.getChannelList().size());
            } else if (idleEvent.state() == IdleState.WRITER_IDLE) {//写
                log.warn("未检测到心跳【写入】");
            } else if (idleEvent.state() == IdleState.ALL_IDLE) {//全部
                log.warn("未检测到心跳【所有】");
            }else{
                log.warn("心跳");
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
